import Storage from '@/utils/storage.js'
const cart = {
	state() {
		return {
			cart: []
		}
	},
	getters: {
		cartGoodsNumber(state) {
			let cartGoodsNumber = 0;
			state.cart.map((item, key) => {
				cartGoodsNumber += item.num
			})
			return cartGoodsNumber
		},
		cartGoodsTotal(state){
			let total = 0;
			for (let i = 0; i < state.cart.length; i++) {
				const elem = state.cart[i];
				if (elem.checked) {
					total = total + (elem.price * elem.num)
				}
			}
			return total;
		}
	},
	mutations: {
		addCart(state, goods) {
			let cart = state.cart;
			if (cart.length == 0) {
				state.cart.push(goods)
			} else {
				// 循环主要目的是判断是否已经有商品在购物车了 有就是加数据
				let isHas = false;
				for (let i = 0; i < cart.length; i++) {
					// 如果有相同 isHas设置 true
					const elem = cart[i];
					if (elem.goods_id == goods.goods_id && elem.attr_id == goods.attr_id) {
						state.cart[i].num++;
						isHas = true
					}
				}
				// 没有的话添加商品到购物车
				if (!isHas) {
					state.cart.push(goods)
				}
			}
			// 添加完商品后 数据缓存中备一份
			Storage.set("cartGoods", state.cart)
		},
		storageToCart(state) {
			if (Storage.get("cartGoods")) {
				state.cart = Storage.get("cartGoods")
			}
		},
		addGoodsNumber(state, index) {
			state.cart[index].num++;
			Storage.set("cartGoods", state.cart)
		},
		subGoodsNumber(state, index) {
			state.cart[index].num--;
			Storage.set("cartGoods", state.cart)
		},
		setGoodsChecked(state, index) {
			state.cart[index].checked = !state.cart[index].checked;
			console.log(state.cart[index].checked)
			Storage.set("cartGoods", state.cart)
		}
	}
}

export default {
	cart
}
